package avortep.synchro;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import avortep.model.DBModel;
import avortep.model.DBAbstractTable;

public abstract class DBSynchro {
	protected Connection connection;
	protected DBModel model;
	protected DBSqlReader sqlReader;
	
	protected DBSynchro(Connection connection, DBModel model, DBSqlReader dbSqlReader) {
		super();
		this.connection = connection;
		this.model = model;
		this.sqlReader = dbSqlReader;
	}
	
	public void synchronize() throws SQLException, SQLWarning {
		Statement statement = connection.createStatement();		
		loadTables(statement.executeQuery(sqlReader.getSqlGetTables()));
		loadViews(statement.executeQuery(sqlReader.getSqlGetViews()));
		loadColumns(statement.executeQuery(sqlReader.getSqlGetColumns()));
		connection.close();
	}
	
	protected void loadColumns(ResultSet columns) throws SQLException, SQLWarning {
        if (columns!=null)
	        while(columns.next()) {
	        	DBAbstractTable table = (DBAbstractTable) model.getChildByName(sqlReader.getTableName(columns));
	        	if (table==null) 
	        		throw new SQLWarning("Table " + columns.getString(sqlReader.tableName) +" missing. Column was not added");
	        	else{		        	
		        	table.addColumn(sqlReader.getColumn(columns));
	        	}
	        }
	}
	
	protected void loadViews(ResultSet views) throws SQLException {
        if (views!=null)
	        while(views.next()){
	        	model.addTable(sqlReader.getView(views));
	        }
	}
	
	protected void loadTables(ResultSet tables) throws SQLException {
    	if (tables != null)
	        while(tables.next()) {
	        	model.addTable(sqlReader.getTable(tables));
	        }	
	}

}
